//
//  MapLocateViewController.m
//  ConsumeTreasure
//
//  Created by youyoumacmini3 on 16/12/29.
//  Copyright © 2016年 youyou. All rights reserved.
//

#import "MapLocateViewController.h"
#import "DLMapSearchViewController.h"
#import "PostVocherListVIew.h"
#import "ChooseLocationRange.h"
#import "AppDelegate.h"
#import "cityModel.h"
#import "HBJSearchResultModel.h"
#import "KGModal.h"
#import <BaiduMapAPI_Search/BMKSearchComponent.h>

@interface MapLocateViewController ()<
BMKMapViewDelegate,
BMKGeoCodeSearchDelegate,
BMKLocationServiceDelegate,
BMKSuggestionSearchDelegate,
UITableViewDelegate,
UITableViewDataSource
,UISearchBarDelegate>
{
    //BMKPinAnnotationView *newAnnotation;
    
    BMKGeoCodeSearch *_geoCodeSearch;
    
    BMKReverseGeoCodeOption *_reverseGeoCodeOption;
    
    BMKLocationService *_locService;
    BMKPointAnnotation* lockedScreenAnnotation;//锁屏点
    NSString *address;
    BMKCircle* circle;//经度圈
    ChooseLocationRange *locationRangeView;
    UIView *_topbgView;
    NSString *_cityName;
    CLLocationCoordinate2D _pt;
    BOOL isBack;
    BMKPoiSearch* _poisearch;
    int curPage;
    UITextField *textField;
    //搜索地点集合
    NSMutableArray *searchResultArray;
    BMKSuggestionSearchOption *option;
    BMKSuggestionSearch * _searcher;

}
@property (weak, nonatomic) IBOutlet BMKMapView *mapview;
@property (weak, nonatomic) IBOutlet UIButton *mappin;//大头针
@property (weak, nonatomic) IBOutlet UILabel *longtitudelab;//经度
@property (weak, nonatomic) IBOutlet UILabel *latitudelab;//纬度
@property (nonatomic, strong)  NSMutableArray *cityDataArr;
@property (weak, nonatomic) IBOutlet UILabel *arealabel;
@property (weak, nonatomic) IBOutlet UILabel *locationRangeLabel;
@property (weak, nonatomic) IBOutlet UIButton *sendVocherBtn;
@property(nonatomic,strong) NSArray<BMKPoiInfo *> *dataList;//信息
@property (weak, nonatomic) IBOutlet UIView *latAndLonView;
@property (nonatomic, strong) UITableView *cityTableview;
@property (nonatomic,strong)UISearchBar * searchBar;
@property (nonatomic,strong)BMKPointAnnotation* item;

@end

@implementation MapLocateViewController

/**
 发送红包券
 
 @param sender button
 */
- (IBAction)sendVocherBtn:(id)sender {
    PostVocherListVIew *vocherView = [PostVocherListVIew loadNibWithVocher];
    [KGModal sharedInstance].closeButtonType = KGModalCloseButtonTypeNone;
    // [KGModal sharedInstance].tapOutsideToDismiss = NO;
    vocherView.lon = self.longtitudelab.text;
    vocherView.lat = self.latitudelab.text;
    vocherView.tapBlock = ^{
        [[KGModal sharedInstance] hide];
    };
    [KGModal sharedInstance].modalBackgroundColor = [UIColor whiteColor];
    [[KGModal sharedInstance] showWithContentView:vocherView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initLocationService];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _poisearch = [[BMKPoiSearch alloc]init];
    [self addNavBarBtn];
    
    [self setupSearcher];
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapview viewWillAppear];
    _mapview.delegate = self;
    _locService.delegate = self;
    _mapview.showsUserLocation = YES;
    _mapview.showsUserLocation = NO;//先关闭显示的定位图层
    _mapview.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
    _mapview.showsUserLocation = YES;//显示定位图层
    _searcher.delegate = self;
    //FIXME:- xiugai
    [self addNavBarBtn];
    // 此处记得不用的时候需要置nil，否则影响内存的释放
    
    if ([[MYXMemberMdel sharedInstance].userinfo.phone isEqualToString:KLebronAccount]) {
        self.sendVocherBtn.hidden = NO;
        self.latAndLonView.hidden = NO;
    }
    
    [_locService startUserLocationService];

}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_mapview viewWillDisappear];
    [_locService stopUserLocationService];
    //[_mapview removeFromSuperview];
    _mapview.delegate = nil;
    _locService.delegate = nil;
    _poisearch.delegate = nil;
    _searcher.delegate = nil;
    // 不用时，置nil
    
}
#pragma mark -PrivateMethod

- (void)backNav{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)addNavBarBtn{
    self.navigationController.navigationBarHidden = NO;
    
    UIButton *sureBtn = [[UIButton alloc] init];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(sureBtnAct) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:sureBtn];
    
    
}
- (void)sureBtnAct{
    [[NSNotificationCenter defaultCenter] postNotificationName:PostChangeLocationRangeName object:self.rangeModel];

    [self.navigationController popViewControllerAnimated:YES];
}
+ (MapLocateViewController *)loadNibWithMapLocationVC{
    UINib *nib = [UINib nibWithNibName:@"MapLocateViewController" bundle:[NSBundle mainBundle]];
    return [[nib instantiateWithOwner:nil options:nil] lastObject];
}


#pragma mark 初始化地图，定位
-(void)initLocationService
{
    self.cityDataArr = [NSMutableArray arrayWithCapacity:10];
    [_mapview setMapType:BMKMapTypeStandard];// 地图类型 ->卫星／标准、
    
    _mapview.zoomLevel=17;
    _mapview.showsUserLocation = YES;
    
    //  [_mapview bringSubviewToFront:_mappin];
    
    
    if (_locService==nil) {
        _locService = [[BMKLocationService alloc]init];
        [_locService setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    }
    
    //  _locService.delegate = self;
    
    CGPoint centerPoint = self.view.center;
    NSLog(@"center Point is %f",centerPoint.y);
    if (lockedScreenAnnotation == nil) {
        lockedScreenAnnotation = [[BMKPointAnnotation alloc] init];
        lockedScreenAnnotation.isLockedToScreen = YES;
        lockedScreenAnnotation.screenPointToLock = CGPointMake(_mapview.bounds.size.width/2, _mapview.bounds.size.height/2);
    }
    [_mapview addAnnotation:lockedScreenAnnotation];
}

#pragma mark BMKLocationServiceDelegate
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    
    NSString *normalAnnotationId = @"normalAnnotationId";
    BMKPinAnnotationView *normalAnnotaitonView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:normalAnnotationId];
    normalAnnotaitonView.draggable = YES;
    normalAnnotaitonView.pinColor = BMKPinAnnotationColorRed;
    normalAnnotaitonView.animatesDrop = NO;// 设置该标注点动画显示
    normalAnnotaitonView.image = [UIImage imageNamed:@"media_annotionImage"];
    
    // 设置位置
    normalAnnotaitonView.centerOffset = CGPointMake(0, -(normalAnnotaitonView.frame.size.height * 0.5));
    normalAnnotaitonView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    normalAnnotaitonView.canShowCallout = YES;
    // 设置是否可以拖拽
    normalAnnotaitonView.draggable = YES;
    
    
    return normalAnnotaitonView;
}
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    _mapview.showsUserLocation = YES;//显示定位图层
    [_mapview updateLocationData:userLocation];
}
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error{
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapview.annotations];
    [_mapview removeAnnotations:array];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        
        isBack = YES;
        
        NSMutableArray *annotations = [NSMutableArray array];
        //        for (int i = 0; i < result.poiInfoList.count; i++) {
        BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:1];
        _item = [[BMKPointAnnotation alloc]init];
        _item.coordinate = poi.pt;
        _item.title = poi.name;
        NSLog(@"%f---,%f",_item.coordinate.latitude,_item.coordinate.longitude);
        [annotations addObject:_item];
        // }
        [_mapview addAnnotations:annotations];
        [_mapview showAnnotations:annotations animated:YES];
        
        NSLog(@"%@",annotations);
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
    } else {
        // 各种情况的判断。。。
    }
}

#pragma mark BMKMapViewDelegate
- (BMKOverlayView*)mapView:(BMKMapView *)mapView viewForOverlay:(id<BMKOverlay>)overlay{
    if ([overlay isKindOfClass:[BMKCircle class]])
    {
        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor = [[UIColor alloc] initWithRed:1 green:0 blue:0 alpha:0.22];
       // circleView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.5];
       // circleView.lineWidth = 0.2;
        
        return circleView;
    }
    return nil;
}
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView{
    
    
    BMKCoordinateRegion region ;//表示范围的结构体
    region.center = _mapview.centerCoordinate;//中心点
    NSInteger multiple = self.rangeModel.locationRangeRadius > 1000 ? 1 : 0.1;
    region.span.latitudeDelta = 0.04 * multiple;//经度范围（设置为0.1表示显示范围为0.2的纬度范围）
    region.span.longitudeDelta = 0.04 * multiple;//纬度范围
    
    [_mapview setRegion:region animated:YES];
    
}
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    

    //屏幕坐标转地图经纬度
    CLLocationCoordinate2D MapCoordinate=[_mapview convertPoint:_mapview.center toCoordinateFromView:_mapview];
    self.rangeModel.lon = [NSString stringWithFormat:@"%f",MapCoordinate.longitude];
    self.rangeModel.lati = [NSString stringWithFormat:@"%f", MapCoordinate.latitude];
    //设置地图中心为用户经纬度
    BMKCoordinateRegion region ;//表示范围的结构体
    if (isBack) {
        region.center = _item.coordinate;//中心点
    }else{
        region.center = lockedScreenAnnotation.coordinate;//中心点
    }
    NSLog(@"lat %f,litu %f",region.center.latitude,region.center.longitude);
    [_mapview removeOverlay:circle];
    circle = nil;
    if (circle == nil) {
        
        circle = [BMKCircle circleWithCenterCoordinate:region.center radius:self.rangeModel.locationRangeRadius];
    }
    [_mapview addOverlay:circle];
    
    
    //获取经纬度
    self.latitudelab.text = [NSString stringWithFormat:@"%f",MapCoordinate.latitude];
    self.longtitudelab.text = [NSString stringWithFormat:@"%f",MapCoordinate.longitude];
    
    if (_geoCodeSearch==nil){
        //初始化地理编码类
        _geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
        _geoCodeSearch.delegate = self;
    }
    
    if (_reverseGeoCodeOption==nil) {
        //初始化反地理编码类
        _reverseGeoCodeOption= [[BMKReverseGeoCodeOption alloc] init];
    }
    
    //需要逆地理编码的坐标位置
    _reverseGeoCodeOption.reverseGeoPoint =MapCoordinate;
    [_geoCodeSearch reverseGeoCode:_reverseGeoCodeOption];
    isBack = NO;
}

#pragma mark BMKGeoCodeSearchDelegate
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    //获取周边用户信息
    if (error==BMK_SEARCH_NO_ERROR) {
        address = result.address;
        self.arealabel.text = address;
        [self.cityDataArr removeAllObjects];
        
        for(BMKPoiInfo *poiInfo in result.poiList)
        {
            cityModel *model=[[cityModel alloc]init];
            model.name=poiInfo.name;
            model.address=poiInfo.address;
            //            CLLocationCoordinate2D _pt;
            self.dataList = result.poiList;
            _cityName = result.addressDetail.city;
            
            [self.cityDataArr addObject:model];
            [self.cityTableview reloadData];
        }
    }else{
        NSLog(@"BMKSearchErrorCode: %u",error);
    }
}

//实现Delegate处理回调结果
- (void)onGetSuggestionResult:(BMKSuggestionSearch*)searcher result:(BMKSuggestionResult*)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        if (searchResultArray.count != 0) {
            [searchResultArray removeAllObjects];
        }
        //在此处理正常结果
        for (int i = 0; i < result.keyList.count; i++) {
            HBJSearchResultModel *model = [[HBJSearchResultModel alloc]init];
            model.name = result.keyList[i];
            CLLocationCoordinate2D coor;
            [result.ptList[i] getValue:&coor];
            model.kCoordinate = coor;
            [searchResultArray addObject:model];
        }
        [self.cityDataArr removeAllObjects];
        [self showLocations];
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

#pragma mark -BtnActionDelegate
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)back:(id)sender {
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)sureBtn:(id)sender {
    
    if (locationRangeView == nil) {
        locationRangeView = [ChooseLocationRange loadNibChooseView];
    }
    [[KGModal sharedInstance] setCloseButtonType:KGModalCloseButtonTypeNone];
    [KGModal sharedInstance].modalBackgroundColor = [UIColor whiteColor];
    [[KGModal sharedInstance] showWithContentView:locationRangeView andAnimated:YES];
    __weak typeof(self) weakself = self;
   __block BMKMapView * weakMapview = _mapview;
    __block  BMKCircle* weakCircle = circle;
    locationRangeView.chooseBlock = ^(NSInteger index){
        switch (index) {
            case 0:
                weakself.rangeModel.locationRange = @"1km";
                weakself.locationRangeRadouis = 1000;
                break;
            case 1:
                weakself.rangeModel.locationRange  = @"3km";
                weakself.locationRangeRadouis = 3000;
                break;
            case 2:
                weakself.rangeModel.locationRange = @"5km";
                weakself.locationRangeRadouis = 5000;
                break;
            default:
                break;
        }
        [weakMapview removeOverlay:weakCircle];
        weakself.locationRangeLabel.text = weakself.rangeModel.locationRange;
        weakself.rangeModel.locationRangeRadius = weakself.locationRangeRadouis;
        //设置地图中心为用户经纬度
        BMKCoordinateRegion region ;//表示范围的结构体
        region.center = _mapview.centerCoordinate;//中心点
 //NSLog(@"lat %f,litu %f",region.center.latitude,region.center.longitude);
            circle = nil;
        if (circle == nil) {
            circle = [BMKCircle circleWithCenterCoordinate:region.center radius:weakself.rangeModel.locationRangeRadius];
        }
        [weakMapview addOverlay:circle];
        [weakMapview mapForceRefresh];
        [[KGModal sharedInstance] hide];
    };
}


- (IBAction)selectNearbylocation:(id)sender {
    [searchResultArray removeAllObjects];
    [self showLocations];
}
- (void)showLocations{
    self.cityTableview.hidden = NO;
    [self.cityTableview reloadData];
}

#pragma mark - TableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cityDataArr.count > 1 ? self.cityDataArr.count : searchResultArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellReuseId = @"reuseId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseId forIndexPath:indexPath];
    if (self.cityDataArr.count > 1) {
        cityModel *model = self.cityDataArr[indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%@(%@)",model.address,model.name];
    }else{
        HBJSearchResultModel *searchModel = searchResultArray[indexPath.row];
        cell.textLabel.text = searchModel.name;
    }
    cell.textLabel.font = [UIFont systemFontOfSize:10];

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.cityDataArr.count > 0) {
        cityModel *model = self.cityDataArr[indexPath.row];
        self.arealabel.text = [NSString stringWithFormat:@"%@(%@)",model.address,model.name];
    }else{
        HBJSearchResultModel *searchModel = searchResultArray[indexPath.row];
        self.arealabel.text = searchModel.name;
        //FIXME:添加跳转地图
       // [_mapview removeOverlay:circle];
        [_mapview setCenterCoordinate:searchModel.kCoordinate animated:YES];
    }
    self.cityTableview.hidden = YES;
   // [[KGModal sharedInstance] hideAnimated:YES];
}
#pragma mark -Setter
- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
        _searchBar.backgroundColor = [UIColor clearColor];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"请输入目的地";
        _searchBar.showsCancelButton = NO;
        [self.view addSubview:_searchBar];
        
    }
    return _searchBar;
}
#pragma mark - searchBar代理
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar __TVOS_PROHIBITED
{
    searchBar.showsCancelButton = NO;
    if (!self.searchBar.isHidden) {
        //        [searchView removeFromSuperview];
    }
    [searchBar resignFirstResponder];
    [searchResultArray removeAllObjects];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    option = [[BMKSuggestionSearchOption alloc] init];
    option.cityname = ApplicationDelegate.mCityName;
    option.keyword = searchText;
    [_searcher suggestionSearch:option];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    option = [[BMKSuggestionSearchOption alloc] init];
    option.cityname = ApplicationDelegate.mCityName;
    option.keyword = searchBar.text;
    [_searcher suggestionSearch:option];
    [searchBar resignFirstResponder];
}
//初始化搜索
- (void)setupSearcher
{
    //初始化列表
    self.cityTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, ScreenWidth, 240) style:UITableViewStylePlain];
    [self.cityTableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuseId"];
    self.cityTableview.delegate = self;
    self.cityTableview.dataSource = self;
    self.cityTableview.hidden = YES;
    [self.view addSubview:self.cityTableview];
    //初始化检索对象
    searchResultArray = [NSMutableArray array];
    _searcher =[[BMKSuggestionSearch alloc]init];
    option = [[BMKSuggestionSearchOption alloc] init];
    option.cityname = ApplicationDelegate.mCityName;
    option.keyword  = @"";
    BOOL flag = [_searcher suggestionSearch:option];
    if(flag)
    {
        NSLog(@"建议检索发送成功");
    }
    else
    {
        NSLog(@"建议检索发送失败");
    }
    [self.view bringSubviewToFront:self.searchBar];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.cityTableview.hidden = YES;
}
@end

